package com.moji.common.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;

public class Base64Util {
    // 加密
    public static String encrypt(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    // 字节加密
    public static String getBase64(byte[] b) {
        String s = null;
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }

    // 解密
    public static String decrypt(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
//    public static void main(String[] args) throws Exception {
//        String source = "张三";
//        System.out.println("原文: " + source);
//        //String key = "A1B2C3D4E5F60708";
//        String encryptData = encrypt(source);
//        System.out.println("加密后: " + encryptData);
//        String decryptData = decrypt(encryptData);
//        System.out.println("解密后: " + decryptData);
//    }
}
